<h1><?php echo $this->pageTitle; ?></h1>
<?php echo $ajax->form('DeRH', 'post', array('id' => 'formMain', 'update' => 'content', 'indicator' => 'indicator', 'url' => array('action' => 'save'))); ?>

<div class="toolbar">
    <div id="tLeft">
        <?php
        if ($mode == 'acknowledge' || $mode == 'request_cancel') {
            echo $this->element('toolbar', array('buttons' => array('save', 'clear', 'back')));
        } else {
            if (in_array($status_id, array(DeRStatus::ON_REQUEST))) {
                echo $this->element('toolbar', array('buttons' => array('delivery_acknowledge', 'request_cancel', array('print' => array('model' => 'DeRH')), 'back')));
            } elseif ($status_id == DeRStatus::ACKNOWNLEDGE && $mode == 'view') {
                echo $this->element('toolbar', array('buttons' => array('request_cancel', 'delivery', array('print' => array('model' => 'DeRH')), 'back')));
            } else {
                echo $this->element('toolbar', array('buttons' => array(array('print' => array('model' => 'DeRH')), 'back')));
            }
        }
        ?>
    </div>
    <div id="tRight"><?php echo $this->element('neighbors', array('model' => 'DeRH', 'title' => 'request_no')); ?></div>
</div>

<?php echo $form->input('DeRH.id'); ?>
<?php echo $form->hidden('DeRH.delivery_request_status_id'); ?>
<?php echo $form->hidden('mode', array('value' => $mode, 'id' => 'mode', 'name' => 'data[mode]')); ?>
<fieldset>
    <table>
        <tr>
            <td width="120px"><?php echo $form->label('DeRH.request_no', 'Request no'); ?></td>
            <td width="300px">
                <?php
                echo $html->tag('span', $this->data['DeRH']['request_no']);
                if ($this->data['DeRH']['is_returned']) {
                    echo $html->link(' ' . ($this->data['DeRtH']['delivery_return_status_id'] == DeRtStatus::RETURNING ? $html->image('icon/return2.png') : $html->image('icon/return.png')), array('controller' => 'delivery_returns', 'action' => 'view', 'delivery_request_head_id:' . $this->data['DeRH']['id']), array('target' => '_blank'), null, false);
                }
                ?>
            </td>
            <td width="150px"><?php echo $form->label('DeRH.customer_id', 'Customer'); ?></td>
            <td><?php echo $this->data['Customer']['name']; ?></td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRH.request_date', 'Request date'); ?></td>
            <td><?php echo $html->tag('span', $this->data['DeRH']['request_date']); ?></td>
            <td><?php echo $form->label('DeRH.site_id', 'Site'); ?></td>
            <td><?php echo $this->data['Site']['name']; ?></td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRH.request_by', 'Request by'); ?></td>
            <td><?php echo $html->tag('span', $this->data['DeRH']['request_by']); ?></td>
            <td><?php echo $form->label('DeRH.due_date', 'Request Delivery Date'); ?></td>
            <td><?php echo $html->tag('span', $this->data['DeRH']['due_date']); ?></td>
        </tr>
        <tr>
            <td><?php echo $form->label('DeRH.deliver_status_id', 'Delivery Status'); ?></td>
            <td><?php echo $this->data['DeRStatus']['title'] . ($this->data['DeRH']['is_partial'] ? ' (Partial)' : ''); ?></td>
            <td><?php echo $form->label('DeRH.supplier_due_date', 'Actual Delivery Date'); ?></td>
            <td>
                <?php
                // อยู่ในช่วงที่แก้ไขวันที่ได้
                if ($mode == 'acknowledge') {
                    echo $form->text('DeRH.supplier_due_date', array('value' => !empty($this->data['DeRH']['supplier_due_date']) ? $this->data['DeRH']['supplier_due_date'] : $this->data['DeRH']['due_date']));
                } else {
                    echo $this->data['DeRH']['supplier_due_date'];
                }
                ?>
            </td>
        </tr>
    </table>
</fieldset>

<fieldset>
    <table class="data">
        <thead>
            <tr>
                <th width="35px">No</th>
                <th width="150px">Part no.</th>
                <th width="120px">Stock code</th>
                <th>Description</th>
                <th width="100px">
                    Request Qty.
                </th>
                <?php if ($status_id > DeRStatus::ON_DELIVERY) { ?>
                    <th width="90px">Receive Qty.</th>
                <?php } ?>
                <th width="50px">Unit</th>
                <th width="80px">Price / Unit</th>
                <th width="80px">Amount</th>
            </tr>
        </thead>
        <tbody id="productRow">
            <?php
            $count = count($this->data['DeR']);
            $total = 0;
            ?>
            <?php for ($i = 0; $i < $count; ++$i) : ?>
                <tr class="<?php echo (($i + 1) % 2 == 0) ? 'even-cell' : 'odd-cell'; ?>">
                    <td><span><?php echo $i + 1; ?></span></td>
                    <td>
                        <?php
                        echo $html->link($this->data['DeR'][$i]['Product']['supplier_part_no'], '/supplier_inventories/view/' . $this->data['DeR'][$i]['cust_product_site_id'] . '/' . strtotime('now'), array('target' => '_blank'));
                        echo $form->hidden("DeR.{$i}.id");
                        ?>
                    </td>
                    <td class="center"><?php echo $this->data['DeR'][$i]['CustProductSite']['stock_code']; ?></td>
                    <td>
                        <?php
                        echo!empty($this->data['DeR'][$i]['CustProductSite']['text']) ?
                                $this->data['DeR'][$i]['CustProductSite']['text'] :
                                $this->data['DeR'][$i]['Product']['text'];
                        ?>
                    </td>
                    <td class="text-right">
                        <?php
//                            if ($status_id == DeRStatus::ON_REQUEST || $mode == 'edit') {
//                                echo $form->text("DeR.{$i}.delivery_qty", array('maxlength' => 3, 'size' => 5, 'class' => 'text-right', 'value' => $this->data['DeRH']['is_partial']? $this->data['DeR'][$i]['delivery_qty']: $this->data['DeR'][$i]['request_qty']));
//                                echo $html->tag('span', '/' . $this->data['DeR'][$i]['request_qty'], array('id' => "DeR{$i}MaxRequestQty"));
//                            } else {
                        echo $this->data['DeR'][$i]['request_qty'];
                        echo $form->hidden("DeR.{$i}.delivery_qty", array('value' => $this->data['DeR'][$i]['request_qty']));
                        $qty = $this->data['DeR'][$i]['request_qty'];
//                            }
                        ?>
                    </td>
                    <?php if ($status_id > DeRStatus::ON_DELIVERY) { ?>
                        <td class="text-right">
                            <?php
                            echo empty($this->data['DeR'][$i]['receive_qty']) ? '-' : $this->data['DeR'][$i]['receive_qty'];
                            $qty = $this->data['DeR'][$i]['receive_qty'];
                            ?>
                        </td>
                    <?php } ?>
                    <td class="center"><?php echo $this->data['DeR'][$i]['Product']['Unit']['title']; ?></td>
                    <td class="text-right">
                        <span id="spanDeRPrice<?php echo $i; ?>"><?php echo number_format($this->data['DeR'][$i]['price'], 2); ?></span>
                        <?php echo $form->hidden("DeR.{$i}.price"); ?>
                    </td>
                    <td class="text-right">
                        <?php
                        $amount = $qty * $this->data['DeR'][$i]['price'];
                        $total += $amount;
                        echo $html->tag('span', number_format($amount, 2), array('id' => "DeR{$i}Amount"));
                        ?>
                    </td>
                </tr>
            <?php endfor; ?>
        </tbody>
        <tfoot id="tableFooter">
            <tr>
                <?php
                if ($status_id > DeRStatus::ON_DELIVERY) {
                    $colspan = 8;
                } else {
                    $colspan = 7;
                }
                ?>
                <td class="text-right" colspan="<?php echo $colspan; ?>">Total</td>
                <td class="text-right">
                    <span id="spanTotal">
                        <?php echo $mode == 'view' ? number_format($total, 2) : ''; ?>
                    </span>
                </td>
            </tr>
        </tfoot>
    </table>
</fieldset>
<fieldset>
    <table>
        <tr>
            <td width="120px" class="top"><?php echo $form->label('DeRH.customer_comment', 'Customer Remark'); ?></td>
            <td><?php echo $this->data['DeRH']['customer_comment'] ? $this->data['DeRH']['customer_comment'] : '-'; ?></td>
        </tr>
        <tr>
            <td class="top"><?php echo $form->label('DeRH.supplier_comment', 'Vendor Remark'); ?></td>
            <td><?php
                        if ($mode == 'acknowledge' || $mode == 'request_cancel') {
                            echo $form->textarea('DeRH.supplier_comment', array('cols' => 80, 'rows' => 3));
                        } else {
                            echo $this->data['DeRH']['supplier_comment'] ? $this->data['DeRH']['supplier_comment'] : '-';
                        }
                        ?>
            </td>
        </tr>
        <?php if ($status_id > DeRStatus::ON_DELIVERY) { ?>
            <tr>
                <td width="50px" class="top"><?php echo $form->label('DeRH.is_invoiced', 'Invoiced'); ?></td>
                <td width="200px">
                    <span id="spanInvoiced">
                        <?php echo $this->data['DeRH']['is_invoiced'] == true ? (!empty($this->data['DeRH']['invoice_no']) ? $this->data['DeRH']['invoice_no'] : 'Yes') : 'No'; ?>
                    </span>
                    <?php
                    if ($this->data['DeRH']['is_invoiced'] != true):
                        ?>
                        <span id="spanInvoicedChecked" style="display: none;">
                            <?php echo $form->checkbox('DeRH.is_invoiced', array('id' => 'DeRHIsInvoiced', 'checked' => $this->data['DeRH']['is_invoiced'])); ?> Yes/No &nbsp;
                            <?php echo $form->text('DeRH.invoice_no', array('id' => 'DeRHInvoiceNo', 'style' => 'display: ' . ($this->data['DeRH']['is_invoiced'] == true ? 'block;' : 'none;'), 'value' => $this->data['DeRH']['invoice_no'])); ?><br />
                            <?php echo $html->link('Save', array('controller' => 'supplier_delivery_requests', 'action' => 'set_invoiced', $this->data['DeRH']['id']), array('id' => 'linkInvoiced', 'class' => 'hide')); ?>
                            <button id="buttonInvoicedChecked">Save</button>
                            <?php echo $html->link('Cancel', '#', array('id' => 'linkCancel')); ?>
                        </span>
                        <script type="text/javascript">
                            $j(function() {
                                var spanChecked = "#spanInvoicedChecked";
                                var spanInvoiced = "#spanInvoiced";
                                var cancel = "#linkCancel";
                                var linkInvoiced = "#linkInvoiced";
                                var button = "#buttonInvoicedChecked";
                                var checkbox = "#DeRHIsInvoiced";
                                var invoiceNo = "#DeRHInvoiceNo";

                                $j(spanInvoiced).handover({highlight: 'td'}).bind('click', function(){
                                    $j(this).hide();
                                    $j(spanChecked).slideDown();
                                });

                                $j(cancel).bind('click', function() {
                                    $j(spanChecked).slideUp();
                                    $j(spanInvoiced).show();
                                });

                                $j(checkbox).bind('click', function() {
                                    if ($j(this).attr('checked')) {
                                        $j(invoiceNo).slideDown();
                                    }  else {
                                        $j(invoiceNo).slideUp();
                                    }
                                });

                                $j(button).bind('click', function(event) {
                                    $j(spanInvoiced).update($j(linkInvoiced).attr('href') + '/' + $j(checkbox).is(':checked') + '/' + escape($j(invoiceNo).val()), function(data) {
                                        if (data == 'Yes') {
                                            var inv = $j(invoiceNo).val();
                                            if (inv.length > 0) {
                                                $j(spanInvoiced).text(inv);
                                            }
                                        }
                                    });
                                    $j(cancel).click();
                                    event.preventDefault();
                                });
                            })
                        </script>
                    <?php endif; ?>
                </td>
                <td>&nbsp;</td>
            </tr>
        <?php } ?>
    </table>
</fieldset>
<?php echo $form->end(); ?>

<?php if (in_array($status_id, array(DeRStatus::READ, DeRStatus::ON_REQUEST))) : ?>
    <script type="text/javascript" >
        $j(function() {
            $j('#DeRHSupplierDueDate') . datepicker(datepicker_options);

            $j(':text[id$=DeliveryQty]').bind('keypress', partNoKeyPress);
            $j(':text[id$=DeliveryQty]').bind('change', function() {
                // cal Amount
                var maxQty = parseInt($j(this).siblings('[id$=MaxRequestQty]').text().substring(1));
                var deliveryQty = parseInt($j(this).val());
                if (deliveryQty < 0) {
                    alert('Delivery quantity at least 0');
                    $j(this).val(0);
                    deliveryQty = 0;
                }

                if (deliveryQty > maxQty) {
                    alert("Please delivery quantity not greater than request quantity")
                    $j(this).val(maxQty);
                }

                var price = parseFloat($j(this).parents('tr').find('[id$=Price]').val());
                var amount = deliveryQty * price;
                $j(this).parents('tr').find('[id$=Amount]').text(amount.toFixed(2));

                // cal total
                var total = 0;
                $j('span[id$=Amount]').each(function() {
                    var amount = parseFloat($j.trim($j(this).text()).replace(',', ''));
                    if (!isNaN(amount)) {
                        total += amount;
                    }
                });
                $j('#spanTotal').text(total.toFixed(2));
            });
        });
    </script>
<?php endif; ?>